package com.gzw.jackyweather;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.ListViewAutoScrollHelper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.gzw.jackyweather.db.City;
import com.gzw.jackyweather.db.County;
import com.gzw.jackyweather.db.Province;
import com.gzw.jackyweather.util.HttpUtil;
import com.gzw.jackyweather.util.Utility;

import org.litepal.crud.DataSupport;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.Inflater;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * Created by JACKYGUO on 2017/1/10.
 */

public class ChooseAreaFragment extends Fragment {

    private ProgressDialog progressDialog;
    private TextView tv_title;
    private Button btn_back;
    private ListView lv;

    private ArrayAdapter<String> adapter;
    private List<String> datalist = new ArrayList<>();

    private List<Province> provinceList;
    private List<City> cityList;
    private List<County> countyList;

    private Province selectedProvince;
    private City selectedCity;
    private County selectedCounty;

    private int currentLevel;//当前选中的级别

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.choose_area, container, false);
        tv_title = (TextView) view.findViewById(R.id.tv_title);
        btn_back = (Button) view.findViewById(R.id.btn_back);
        lv = (ListView) view.findViewById(R.id.lv);
        adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, datalist);
        lv.setAdapter(adapter);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (currentLevel == Contans.LEVEL_PROVINCE) {
                    selectedProvince = provinceList.get(position);
                    queryCities();

                } else if (currentLevel == Contans.LEVEL_CITY) {
                    selectedCity = cityList.get(position);
                    queryCounties();
                } else if (currentLevel == Contans.LEVEL_COUNTY) {
                    selectedCounty = countyList.get(position);
                    String weatherId = selectedCounty.getWeatherId();

                    if (getActivity() instanceof MainActivity) {

                        //第一次默认选择的城市。保存到数据库
                        Intent intent = new Intent(getActivity(), WeatherActivity.class);
                        intent.putExtra("weather_id", weatherId);
                        startActivity(intent);
                        getActivity().finish();
                    } else if (getActivity() instanceof WeatherActivity) {
                        WeatherActivity weatherActivity = (WeatherActivity) getActivity();
                        weatherActivity.dl.closeDrawers();
                        weatherActivity.srl.setRefreshing(true);
                        weatherActivity.requestWeather(weatherId);
                    } else if (getActivity() instanceof CitySettingActivity) {

                        CitySettingActivity citySettingActivity = (CitySettingActivity) getActivity();
                        citySettingActivity.setWeatherId(weatherId);

                    }
                }
            }
        });

        btn_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (currentLevel == Contans.LEVEL_COUNTY) {
                    //查询城市数据
                    queryCities();

                } else if (currentLevel == Contans.LEVEL_CITY) {
                    //查询省数据
                    queryProvinces();
                }
            }
        });

        queryProvinces();
    }

    /**
     * 查询全国的省，先从数据库查询，如果没有，就加载网络数据。
     */
    public void queryProvinces() {
        tv_title.setText("中国");
        btn_back.setVisibility(View.GONE);

        provinceList = DataSupport.findAll(Province.class);

        if (provinceList.size() > 0) {
            datalist.clear();
            for (Province province : provinceList) {
                datalist.add(province.getProvinceName());
            }

            adapter.notifyDataSetChanged();
            lv.setSelection(0);
            currentLevel = Contans.LEVEL_PROVINCE;
            Contans.CURRENTLEVEL = currentLevel;
        } else {
            String url = "http://guolin.tech/api/china";
            //查询服务器数据
            queryFromServer(url, Contans.PROVINCE);
        }
    }

    /**
     * 查询选中省内所有的市，先从数据库查询，如果没有，就加载网络数据。
     */
    public void queryCities() {
        tv_title.setText(selectedProvince.getProvinceName());
        btn_back.setVisibility(View.VISIBLE);
        //查询这个这个数据表中某个省的城市
        cityList = DataSupport.where("provinceid = ?", String.valueOf(selectedProvince.getId())).find(City.class);

        if (cityList.size() > 0) {
            datalist.clear();
            for (City city : cityList) {
                datalist.add(city.getCityName());
            }
            adapter.notifyDataSetChanged();
            lv.setSelection(0);
            currentLevel = Contans.LEVEL_CITY;
            Contans.CURRENTLEVEL = currentLevel;
        } else {

            int provinceCode = selectedProvince.getProvinceCode();

            String url = "http://guolin.tech/api/china/" + provinceCode;
            //查询服务器数据
            queryFromServer(url, Contans.CITY);
        }
    }


    /**
     * 查询选中省内所有的市的县，先从数据库查询，如果没有，就加载网络数据。
     */
    public void queryCounties() {
        tv_title.setText(selectedCity.getCityName());
        btn_back.setVisibility(View.VISIBLE);
        //查询这个这个数据表中某个省的城市
        countyList = DataSupport.where("cityid = ?", String.valueOf(selectedCity.getId())).find(County.class);

        if (countyList.size() > 0) {
            datalist.clear();
            for (County county : countyList) {
                datalist.add(county.getCountyName());
            }
            adapter.notifyDataSetChanged();
            lv.setSelection(0);
            currentLevel = Contans.LEVEL_COUNTY;
            Contans.CURRENTLEVEL = currentLevel;

        } else {

            int provinceCode = selectedProvince.getProvinceCode();
            int cityCode = selectedCity.getCityCode();
            String url = "http://guolin.tech/api/china/" + provinceCode + "/" + cityCode;
            //查询服务器数据
            queryFromServer(url, Contans.COUNTY);
        }
    }

    /**
     * 加载服务器数据
     *
     * @param url  url地址
     * @param type 类型
     */
    private void queryFromServer(String url, final String type) {

        showProressDialog();
        HttpUtil.sendOkHttpRequest(url, new Callback() {

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                String responseText = response.body().string();
                boolean result = false;

                if (Contans.PROVINCE.equals(type)) {
                    result = Utility.handleProvinceResponse(responseText);
                } else if (Contans.CITY.equals(type)) {
                    result = Utility.handleCityResponse(responseText, selectedProvince.getId());
                } else if (Contans.COUNTY.equals(type)) {
                    result = Utility.handleCountyResponse(responseText, selectedCity.getId());
                }

                if (result) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            closeProgressDialog();
                            if (Contans.PROVINCE.equals(type)) {
                                queryProvinces();
                            } else if (Contans.CITY.equals(type)) {
                                queryCities();
                            } else if (Contans.COUNTY.equals(type)) {
                                queryCounties();
                            }
                        }
                    });
                }
            }

            @Override
            public void onFailure(Call call, IOException e) {

                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        closeProgressDialog();
                        Toast.makeText(getContext(), "加载失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    /**
     * 显示进度对话框
     */
    private void showProressDialog() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(getActivity());
            progressDialog.setMessage("拼命加载中...");
            progressDialog.setCanceledOnTouchOutside(false);
        }
        progressDialog.show();
    }

    /**
     * 关闭进度对话框
     */
    private void closeProgressDialog() {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }
}
